

// unciomment if you build application for using on PDA and SqlServerCe is referenced ( off for unittesting)
#define BaseOn
#if BaseOn
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlServerCe;
using System.Text;
#endif

namespace Belmost4PDA.DatabaseWorkPDA
{
    public class DataBase
    {
#if BaseOn
        private SqlCeConnection Connection = null;
        private DataBase()
        {
            Connection = new SqlCeConnection();
        }

        private static DataBase _instance = null;
        public static string ConnectionString = "Data Source = \"\\Storage Card\\BelmostPDA.sdf\"; Password =\"pdabase\"";
        //Connection for Emul        
        //public static string ConnectionString = "Data Source = \"\\Program Files\\Belmost4pda.forms\\BelmostPDA.sdf\"; Password =\"pdabase\"";
        private SqlCeTransaction trans = null;
        private static void Create()
        {
            if (_instance == null)
            {
                _instance = new DataBase();
                try
                {
                    _instance.ConnectToBase(ConnectionString);
                }
                catch(Exception)
                {
                     ConnectionString = "Data Source = \"\\SD Card\\BelmostPDA.sdf\"; Password =\"pdabase\"";
                    _instance.ConnectToBase(ConnectionString);
                }
            }            
        }
        public static SqlCeConnection Get()
        {
            Create();
            return _instance.GetConnection();
        }
        public static void Disconnect()
        {
            Create();
            _instance.DisconnectFromBase();
            _instance = null;
        }

        private void DisconnectFromBase()
        {
            if(trans!=null)
            {
                trans.Commit();
                trans = null;
            }
            Connection.Close();
        }

        private void ConnectToBase(string _string)
        {
            Connection = new SqlCeConnection(_string);
            Connection.Open();
            trans = Connection.BeginTransaction();
        }
        private SqlCeConnection GetConnection()
        {
            return Connection;
        }
#endif

        public static SqlCeTransaction GetTrans()
        {
            Create();
            return _instance.GetTransaction();
        }

        private SqlCeTransaction GetTransaction()
        {
            return trans;
        }

        public static void RestartTransaction()
        {
            Create();
            _instance.trans.Commit(CommitMode.Immediate);
            _instance.trans = _instance.Connection.BeginTransaction();
        }
    }

}
